package com.thinkgsp.jxc.service.impl;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgsp.jxc.model.Customer;
import com.thinkgsp.jxc.model.Dept;
import com.thinkgsp.jxc.model.Emp;
import com.thinkgsp.jxc.model.Inventory;
import com.thinkgsp.jxc.model.InventoryAdd;
import com.thinkgsp.jxc.model.Product;
import com.thinkgsp.jxc.model.ProductBatchNo;
import com.thinkgsp.jxc.model.ProductContact;
import com.thinkgsp.jxc.model.ProductManuf;
import com.thinkgsp.jxc.model.RpContact;
import com.thinkgsp.jxc.persistence.ContactBalanceMapper;
import com.thinkgsp.jxc.persistence.CustomerMapper;
import com.thinkgsp.jxc.persistence.DeptMapper;
import com.thinkgsp.jxc.persistence.EmpMapper;
import com.thinkgsp.jxc.persistence.InventoryAddMapper;
import com.thinkgsp.jxc.persistence.InventoryMapper;
import com.thinkgsp.jxc.persistence.PeriodMapper;
import com.thinkgsp.jxc.persistence.ProductBatchNoMapper;
import com.thinkgsp.jxc.persistence.ProductContactMapper;
import com.thinkgsp.jxc.persistence.ProductMapper;
import com.thinkgsp.jxc.persistence.RpContactMapper;
import com.thinkgsp.jxc.service.DataImportService;
import com.thinkgsp.sys.model.ImportCustomer;
import com.thinkgsp.sys.model.ImportProduct;
import com.thinkgsp.sys.model.SysAccountPeriod;

@Service("dataImportService")
@Transactional
public class DataImportServiceImpl extends GeneralServiceImpl implements
		DataImportService {

	@Autowired
	private PeriodMapper periodMapper;
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private InventoryAddMapper invaddMapper;
	@Autowired
	private ProductBatchNoMapper batchNoMapper;
	@Autowired
	private InventoryMapper invMapper;
	@Autowired
	private ProductContactMapper pcMapper;
	@Autowired
	private CustomerMapper custMapper;
	@Autowired
	private DeptMapper deptMapper;
	@Autowired
	private EmpMapper empMapper;
	@Autowired
	private RpContactMapper contactMapper;
	@Autowired
	private ContactBalanceMapper cbMapper;
	
	public void importData(int year, int period, List<ImportProduct> products,
			List<ImportCustomer> customers) {
		initPeriod(year,period);
		initProduct(products);
		initInvantoryAdd(products);
		initProductBatchNo(products);
		initInventory(products,year,period);
		initProductContact(products,year,period);
		initDept(customers);
		initEmp(customers);
		initCustomer(customers);
		initContactDetail(customers,year,period);
		initContactBalance(customers,year,period);
	}
	/**
	 * 初始化起始期间
	 * @param year
	 * @param period
	 */
	private void initPeriod(int year,int period) {
		periodMapper.clearPeriod();
		SysAccountPeriod accountPeriod = new SysAccountPeriod();
		accountPeriod.setFyear(year);
		accountPeriod.setPeriod(period);
		accountPeriod.setCurrent(true);
		accountPeriod.setBeginDate(new Date(System.currentTimeMillis()));
		periodMapper.insertNextPeriod(accountPeriod);
	}
	
	/**
	 * 初始化产品资料，如果产品表中不存在，则创建
	 * @param products
	 */
	private void initProduct(List<ImportProduct> products) {
		int beginNumber = 1;
		for(ImportProduct ip : products) {
			Product product;
			if(ip.getProductCode() == null || ip.getProductCode().isEmpty()) {
				String productCode = newProductCode(beginNumber);
				beginNumber++;
				ip.setProductCode(productCode);
				product = createNewProduct(ip);
			} else {
				product = productMapper.findProductByCode(ip.getProductCode());
				if(product == null) {
					product = createNewProduct(ip);
				}
			}
			ip.setProductObject(product);
		}
	}
	
	private Product createNewProduct(ImportProduct ip) {
		Product product = new Product();
		product.setProductCode(ip.getProductCode());
		product.setProductName(ip.getProductName());
		product.setProductBusName(ip.getBusName());
		product.setPackSpec(ip.getProductSpec());
		product.setManuf(ip.getManuf());
		product.setUnit(ip.getUnit());
		product.setInnerPack(ip.getInnerPack());
		product.setBoxPack(ip.getBoxPack());
		product.setLicenseNo(ip.getLicenseNo());
		product.setBatchMgr(ip.isBatchMgr());
		product.setBarcode(ip.getBarcode());
		product.setTaxRate(ip.getTaxRate());
		product.setClassifyId(1);
		List<ProductManuf> pms = productMapper.searchManuf(ip.getManuf());
		if(pms.size()>0) {
			product.setManufId(pms.get(0).getManufId());
			product.setProductManuf(pms.get(0));
		} else {
			ProductManuf pm = new ProductManuf();
			pm.setManufName(ip.getManuf());
			productMapper.insertManuf(pm);
			product.setManufId(pm.getManufId());
			product.setProductManuf(pm);
		}
		productMapper.insertProduct(product);
		if(!ip.isBatchMgr()) {
			batchNoMapper.insertEmptyBatchNo(product.getProductId());
		}
		return product;
	}
	
	private String newProductCode(int number) {
		String zero = "000000";
		String no = zero.substring(new Integer(number).toString().length()-1) + number;
		return no;
	}
	
	/**
	 * 初始化存货地址，如果存货地址表中不存在，则创建
	 * @param products
	 */
	private void initInvantoryAdd(List<ImportProduct> products) {
		HashMap<String, InventoryAdd> invadds = new HashMap<String, InventoryAdd>();
		for(ImportProduct ip : products) {
			if(ip.getInvAddress() == null || ip.getInvAddress().isEmpty()) {
				ip.setInvAddress("空地址");
			}
			String add = ip.getInvAddress().trim();
			if(invadds.containsKey(add)) {
				ip.setInvAddObject(invadds.get(add));
			} else {
				InventoryAdd invadd = invaddMapper.findInventoryAddByName(add);
				if(invadd == null) {
					invadd = new InventoryAdd();
					invadd.setInventoryAddName(add);
					invadd.setInventoryType(InventoryAdd.INVENTORY_ADD_BRANCH);
					invaddMapper.insertInventoryAdd(invadd);
					invadds.put(add, invadd);
				}
				ip.setInvAddObject(invadd);
			}
		}
	}
	
	/**
	 * 初始化批号表，如果批号表中不存在，则创建
	 * @param products
	 */
	private void initProductBatchNo(List<ImportProduct> products) {
		batchNoMapper.clearBatchNo();
		
		for(ImportProduct ip : products) {
			ProductBatchNo batchNo = null;
			boolean batchMgr = ip.isBatchMgr();
			if(batchMgr && (ip.getBatchNo() == null || ip.getBatchNo().isEmpty())) {
				ip.setBatchNo("空");
			}
			if(batchMgr) {
				batchNo = batchNoMapper.getBatchNoByProduct(ip.getProductObject().getProductId(), ip.getBatchNo());
				if(batchNo == null) {
					batchNo = new ProductBatchNo();
					batchNo.setProductId(ip.getProductObject().getProductId());
					batchNo.setBatchNo(ip.getBatchNo());
					batchNo.setManufDate(new Date(ip.getManufDate().getTime()));
					batchNo.setExpDate(new Date(ip.getExpDate().getTime()));
					batchNoMapper.insertBatchNo(batchNo);
				}
			} else {
				batchNo = batchNoMapper.getBatchNoByEmpty(ip.getProductObject().getProductId());
			}
			ip.setBatchNoObject(batchNo);
		}
	}
	
	/**
	 * 初始化库存，清空库存表，然后插入
	 * @param products
	 */
	private void initInventory(List<ImportProduct> products,int year,int period) {
		invMapper.clearInventory();
		invMapper.clearBillDetail();
		invMapper.clearBillExtend();
		invMapper.clearBill();
		for(ImportProduct ip : products) {
			Inventory inv = new Inventory();
			inv.setInvAddId(ip.getInvAddObject().getId());
			inv.setProductId(ip.getProductObject().getProductId());
			inv.setBatchNoId(ip.getBatchNoObject().getId());
			inv.setFyear(year);
			inv.setPeriod(period);
			inv.setBeginQty(ip.getQuantity());
			inv.setCostPrice(ip.getPrice());
			inv.setBeginAmt(ip.getQuantity().multiply(ip.getPrice()));
			invMapper.insertInventory(inv);
			ip.setInventoryObject(inv);
		}
	}
	
	private void initProductContact(List<ImportProduct> products,int year,int period) {
		pcMapper.clearProductContact();
		for(ImportProduct ip : products) {
			ProductContact pc = new ProductContact();
			pc.setInvAddId(ip.getInvAddObject().getId());
			pc.setProductId(ip.getProductObject().getProductId());
			pc.setBatchNoId(ip.getBatchNoObject().getId());
			pc.setFyear(year);
			pc.setPeriod(period);
			pc.setRemQty(ip.getQuantity());
			pc.setRemAmt(ip.getQuantity().multiply(ip.getPrice()));
			pc.setBillDate(new Date(System.currentTimeMillis()));
			pc.setCustomerId(0);
			pc.setDirect(0);
			pc.setSummary("系统初始化");
			pcMapper.recordInit(pc);
		}
	}
	
	/**
	 * 初始化客户资料，如果不存在则创建
	 * @param customers
	 */
	private void initCustomer(List<ImportCustomer> customers) {
		int beginNumber = 1;
		for(ImportCustomer ic : customers) {
			Customer cust = null;
			if(ic.getCustNo() == null || ic.getCustNo().isEmpty()) {
				ic.setCustNo(newCustCode(beginNumber));
				beginNumber++;
				cust = createCustomer(ic);
			} else {
				cust = custMapper.getCustByCode(ic.getCustNo());
				if(cust == null) {
					cust = createCustomer(ic);
				}
			}
			ic.setCustomerObject(cust);
		}
	}
	
	private String newCustCode(int num) {
		String zero = "000000";
		String no = zero.substring(new Integer(num).toString().length()-1) + num;
		return no;
	}
	
	private Customer createCustomer(ImportCustomer ic) {
		Customer cust = new Customer();
		cust.setParentId(0);
		cust.setCustomerCode(ic.getCustNo());
		cust.setCustomerName(ic.getCustName());
		cust.setCustType(ic.getCustType());
		cust.setContactMan(ic.getContactMan());
		cust.setTelephone(ic.getTelephone());
		cust.setMobilephone(ic.getMobilephone());
		cust.setQqNumber(ic.getQq());
		cust.setEmail(ic.getEmail());
		cust.setAddress(ic.getCompanyAdd());
		cust.setDeliveryAdd(ic.getDeliveryAdd());
		cust.setDeptId(ic.getDeptObject().getDeptId());
		cust.setEmpId(ic.getEmpObject().getEmpId());
		custMapper.insertCust(cust);
		return cust;
	}
	
	/**
	 * 初始化部门，如果不存在则创建
	 * @param customers
	 */
	private void initDept(List<ImportCustomer> customers) {
		HashMap<String, Dept> depts = new HashMap<String, Dept>();
		for(ImportCustomer ic : customers) {
			Dept dept = null;
			if(ic.getDeptName() == null || ic.getDeptName().isEmpty()) {
				ic.setDeptName("空");
			}
			String deptName = ic.getDeptName().trim();
			if(depts.containsKey(deptName)) {
				ic.setDeptObject(depts.get(deptName));
			} else {
				dept = deptMapper.findDeptByName(deptName);
				if(dept == null) {
					dept = new Dept();
					dept.setDeptName(deptName);
					deptMapper.insertDept(dept);
				} 
				depts.put(deptName, dept);
				ic.setDeptObject(dept);
			}
		}
	}
	
	/**
	 * 初始化职员表，如果不存在则创建
	 * @param customers
	 */
	private void initEmp(List<ImportCustomer> customers) {
		HashMap<String, Emp> emps = new HashMap<String, Emp>();
		for(ImportCustomer ic : customers) {
			Emp emp = null;
			if(ic.getEmpName() == null || ic.getEmpName().isEmpty()) {
				ic.setEmpName("空");
			}
			String empName = ic.getEmpName().trim();
			if(emps.containsKey(empName)) {
				ic.setEmpObject(emps.get(empName));
			} else {
				emp = empMapper.findEmpByName(empName);
				if(emp == null) {
					emp = new Emp();
					emp.setEmpName(empName);
					emp.setDeptId(ic.getDeptObject().getDeptId());
					empMapper.insertEmp(emp);
				}
				emps.put(empName, emp);
				ic.setEmpObject(emp);
			}
		}
	}
	
	/**
	 * 初始化往来明细表
	 * @param customers
	 */
	private void initContactDetail(List<ImportCustomer> customers,int year,int period) {
		contactMapper.clearRpBillDetail();
		contactMapper.clearArpBill();
		contactMapper.clearRpBill();
		contactMapper.clearCheckLog();
		contactMapper.clearRpContact();
		for(ImportCustomer ic : customers) {
			if(ic.getArecAmount().compareTo(BigDecimal.ZERO) != 0) {
				RpContact contact = new RpContact();
				contact.setDirect(1);
				contact.setTypeId(1);
				contact.setBillDate(new Date(System.currentTimeMillis()));
				contact.setCustSuppId(ic.getCustomerObject().getCustomerId());
				contact.setDeptId(ic.getDeptObject().getDeptId());
				contact.setEmpId(ic.getEmpObject().getEmpId());
				contact.setAmount(ic.getArecAmount());
				contact.setRemAmount(ic.getArecAmount());
				contact.setCheckStatus(0);
				contact.setRemark("系统初始化余额");
				contact.setFyear(year);
				contact.setPeriod(period);
				contactMapper.insertContact(contact);
			}
			if(ic.getApayAmount().compareTo(BigDecimal.ZERO) != 0) {
				RpContact contact = new RpContact();
				contact.setDirect(-1);
				contact.setTypeId(RpContact.CONTACT_TYPE_APAY_BILL);
				contact.setBillDate(new Date(System.currentTimeMillis()));
				contact.setCustSuppId(ic.getCustomerObject().getCustomerId());
				contact.setDeptId(ic.getDeptObject().getDeptId());
				contact.setEmpId(ic.getEmpObject().getEmpId());
				contact.setAmount(ic.getArecAmount());
				contact.setRemAmount(ic.getArecAmount());
				contact.setCheckStatus(0);
				contact.setRemark("系统初始化余额");
				contact.setFyear(year);
				contact.setPeriod(period);
				contactMapper.insertContact(contact);
			}
		}
	}
	/**
	 * 初始化往来余额表
	 * @param customers
	 */
	private void initContactBalance(List<ImportCustomer> customers,int year,int period) {
		cbMapper.clearContactBalance();
		for(ImportCustomer ic : customers) {
			if(ic.getArecAmount().compareTo(BigDecimal.ZERO) != 0) {
				if(configuration.getArpCheckObject().equals(Configuration.ARP_CHECK_OBJECT_EMP)) {
					cbMapper.initContactBalanceByEmp(1, year, period, ic.getCustomerObject().getCustomerId(), 
							ic.getDeptObject().getDeptId(), ic.getEmpObject().getEmpId(), ic.getArecAmount());
				} else {
					cbMapper.initContactBalanceByEmp(1, year, period, ic.getCustomerObject().getCustomerId(), 
							ic.getDeptObject().getDeptId(), null, ic.getArecAmount());
				}
			}
			if(ic.getApayAmount().compareTo(BigDecimal.ZERO) != 0) {
				if(configuration.getArpCheckObject().equals(Configuration.ARP_CHECK_OBJECT_EMP)) {
					cbMapper.initContactBalanceByEmp(-1, year, period, ic.getCustomerObject().getCustomerId(), 
							ic.getDeptObject().getDeptId(), ic.getEmpObject().getEmpId(), ic.getApayAmount());
				} else {
					cbMapper.initContactBalanceByEmp(-1, year, period, ic.getCustomerObject().getCustomerId(), 
							ic.getDeptObject().getDeptId(), null, ic.getApayAmount());
				}
			}
		}
	}

}
